<?php
if(!defined('SABLOG_ROOT')) {
	exit('Access Denied');
}
// 获得文件扩展名
function getextension($filename) {
	$pathinfo = pathinfo($filename);
	return $pathinfo['extension'];
}

	$m = $_GET['m'] ? $_GET['m'] : $_POST['m'];

	$addquery = $pagelink = '';
	$subnav = '全部案例';
	if ($_GET['tag']) {
		$item = sax_addslashes($_GET['tag']);
		$tag = $DB->fetch_one_array("SELECT caseids FROM {$db_prefix}tags WHERE tag='$item' LIMIT 1");
		if (!$tag) {
			redirect('标签不存在', 'cp.php?job=caselib&action=list');
		}
		$addquery .= " AND a.articleid IN (".$tag['caseids'].")";
		$subnav = 'Tags:'.$item;
		$pagelink .= '&tag='.urlencode($item);
	}
	if ($m) {
		$mdb = explode('-', $m);
		list($start, $end) = explode('-', gettimestamp($mdb[0],$mdb[1]));
		$pagelink .= '&m='.$m;
		$subnav = '在'.$mdb[0].'年'.$mdb[1].'月里';
		//*******************************//
		$addquery .= " AND dateline >= '".correcttime($start)."' AND dateline < '".correcttime($end)."' ";
	}
	// 搜索部分
	$keywords = sax_addslashes(trim($_POST['keywords'] ? $_POST['keywords'] : $_GET['keywords']));
	if ($keywords) {
		$keywords = str_replace("_","\_",$keywords);
		$keywords = str_replace("%","\%",$keywords);
		if(preg_match("(AND|\+|&|\s)", $keywords) && !preg_match("(OR|\|)", $keywords)) {
			$andor = ' AND ';
			$sqltxtsrch = '1';
			$keywords = preg_replace("/( AND |&| )/is", "+", $keywords);
		} else {
			$andor = ' OR ';
			$sqltxtsrch = '0';
			$keywords = preg_replace("/( OR |\|)/is", "+", $keywords);
		}
		$keywords = str_replace('*', '%', addcslashes($keywords, '%_'));
		foreach(explode("+", $keywords) AS $text) {
			$text = trim($text);
			if($text) {
				$sqltxtsrch .= $andor;
				$sqltxtsrch .= "(description LIKE '%".$text."%' OR title LIKE '%".$text."%')";
			}
		}
		$addquery .= " AND ($sqltxtsrch)";
		$subnav = '搜索结果';
		$pagelink .= '&keywords='.urlencode($keywords);
	}

	$pagenum = 20;
	if($page) {
		$start_limit = ($page - 1) * $pagenum;
	} else {
		$start_limit = 0;
		$page = 1;
	}
	$rs = $DB->fetch_one_array("SELECT * FROM {$db_prefix}caselib WHERE 1 $addquery");
	$total = $rs['caselib'];
	$multipage = multi($total, $pagenum, $page, 'cp.php?job=caselib&action=list'.$pagelink);

	$query = $DB->query("SELECT caseid,title,description,dateline,filename,downloads,visible,permission FROM {$db_prefix}caselib WHERE 1 $addquery ORDER BY dateline DESC LIMIT $start_limit, $pagenum");

	$casedb = array();
    while ($case = $DB->fetch_array($query)) {
		$case['dateline'] = sadate('Y-m-d',$case['dateline']);
		$case['ext'] = getextension($case['filename']);
		$case['url'] = $options['url']."attachment.php?id=".$case['caseid']."&tb=caselib";
		$casedb[] = $case;
	}
	unset($case);
	$DB->free_result($query);


$options['title'] = "康腾案例库";
$pagefile = 'caselib';
?>